package com.github.pig.daemon.job.listener;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.dangdang.ddframe.job.executor.ShardingContexts;
import com.dangdang.ddframe.job.lite.api.listener.AbstractDistributeOnceElasticJobListener;
import com.github.pig.daemon.job.constant.enums.EnumJobTaskStatus;
import com.github.pig.daemon.job.entity.JobTask;
import com.github.pig.daemon.job.mapper.JobTaskMapper;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by IntelliJ IDEA.
 *
 * @author luoliang
 * @date 2018/4/9
 * 实现分布式任务监听器
 * 如果任务有分片，分布式监听器会在总的任务开始前执行一次，结束时执行一次
 **/
public class ElasticJobListener extends AbstractDistributeOnceElasticJobListener {

    @Autowired
    private JobTaskMapper jobTaskMapper;

    public ElasticJobListener(long startedTimeoutMilliseconds, long completedTimeoutMilliseconds) {
        super(startedTimeoutMilliseconds, completedTimeoutMilliseconds);
    }

    @Override
    public void doBeforeJobExecutedAtLastStarted(ShardingContexts shardingContexts) {
    }

    @Override
    public void doAfterJobExecutedAtLastCompleted(ShardingContexts shardingContexts) {
        //任务执行完成后更新状态为已执行
        JobTask jobTask = jobTaskMapper.selectById(Long.valueOf(shardingContexts.getJobParameter()));
        jobTask.setStatus(EnumJobTaskStatus.EXECUTED.getCode());
        JobTask condition = new JobTask();
        jobTaskMapper.update(jobTask,new EntityWrapper<>(condition));    }

}
